<template>
  <div class="banzhu-dashboard">
    <!-- 学生归宿统计柱状图 -->
    <div class="chart-card">
      <violation-bar-chart />
    </div>

    <!-- 学生获奖信息表格 -->
    <div class="table-card">
      <div class="table-header">
        <h2 class="table-title">班级学生获奖信息</h2>
        <div class="table-actions">
          <el-input
            v-model="searchQuery"
            placeholder="输入学号或姓名搜索"
            clearable
            style="width: 300px; margin-right: 10px;"
            @clear="handleSearchClear"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="handleSearch" />
            </template>
          </el-input>
          <el-button-group>
            <el-button 
              type="primary" 
              icon="el-icon-download" 
              @click="handleExport"
              :loading="exportLoading"
            >导出</el-button>
          </el-button-group>
        </div>
      </div>

      <el-table
        :data="filteredAwards"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="studentId" label="学号" width="120" sortable align="center" />
        <el-table-column prop="studentName" label="学生姓名" width="120" align="center" />
        <el-table-column prop="awardName" label="获奖名称" min-width="180" />
        <el-table-column prop="awardLevel" label="获奖级别" width="150" align="center">
          <template #default="{row}">
            <el-tag :type="getLevelTagType(row.awardLevel)" effect="dark">
              {{ row.awardLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="awardDate" label="获奖日期" width="150" sortable align="center" />
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import ViolationBarChart from '@/components/ViolationBarChart.vue'
import { listReward, exportReward } from '@/api/classinfo/classinfo'
import * as XLSX from 'xlsx'

export default {
  name: 'BanzhuHome',
  components: {
    ViolationBarChart
  },
  data() {
    return {
      awards: [],
      loading: false,
      exportLoading: false,
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      sortProp: '',
      sortOrder: ''
    }
  },
  computed: {
    filteredAwards() {
      let result = this.awards
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(item =>
          item.studentId.toLowerCase().includes(query) ||
          item.studentName.toLowerCase().includes(query)
        )
      }

      if (this.sortProp && this.sortOrder) {
        result = [...result].sort((a, b) => {
          const aVal = a[this.sortProp]
          const bVal = b[this.sortProp]
          return this.sortOrder === 'ascending' 
            ? aVal.localeCompare(bVal)
            : bVal.localeCompare(aVal)
        })
      }

      this.total = result.length
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return result.slice(start, end)
    }
  },
  methods: {
    getLevelTagType(level) {
      const map = {
        '国家级': 'danger',
        '省级': 'warning',
        '市级': '',
        '校级': 'success',
        '院级': 'info'
      }
      return map[level] || 'primary'
    },
    
    async fetchAwards() {
      try {
        this.loading = true
        const response = await listReward({
          studentId: this.searchQuery,
          studentName: this.searchQuery
        })
        this.awards = response.rows.map(item => ({
          id: item.id,
          studentId: item.studentId,
          studentName: item.studentName,
          awardName: item.rewardName,
          awardLevel: item.rewardLevel,
          awardDate: item.rewardTime
        }))
        this.total = response.total
      } catch (error) {
        this.$message.error('获取获奖数据失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    handleSearch() {
      this.currentPage = 1
      this.fetchAwards()
    },
    
    handleSearchClear() {
      this.searchQuery = ''
      this.currentPage = 1
      this.fetchAwards()
    },
    
    handleSortChange({ prop, order }) {
      this.sortProp = prop
      this.sortOrder = order
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
    },
    
    async handleExport() {
      try {
        this.exportLoading = true
        
        // 两种导出方式可选：
        // 1. 前端导出（适合数据量小的情况）
        // 2. 后端导出（适合数据量大或需要复杂处理的情况）
        
        // 方式1：前端导出（使用xlsx库）
        await this.exportFrontend()
        
        // 方式2：后端导出（需要后端支持）
        // await this.exportBackend()
        
      } catch (error) {
        this.$message.error('导出失败: ' + error.message)
      } finally {
        this.exportLoading = false
      }
    },
    
    // 前端导出Excel
    async exportFrontend() {
      // 获取所有数据（不筛选不分页）
      const response = await listReward({
        studentId: this.searchQuery,
        studentName: this.searchQuery
      })
      
      const allData = response.rows.map(item => ({
        学号: item.studentId,
        学生姓名: item.studentName,
        获奖名称: item.rewardName,
        获奖级别: item.rewardLevel,
        获奖日期: item.rewardTime
      }))
      
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      // 创建工作表
      const ws = XLSX.utils.json_to_sheet(allData)
      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(wb, ws, '学生获奖信息')
      // 导出Excel文件
      XLSX.writeFile(wb, `学生获奖信息_${new Date().toLocaleDateString()}.xlsx`)
      
      this.$message.success('导出成功')
    },
    
    // 后端导出Excel
    async exportBackend() {
      const response = await exportReward({
        studentId: this.searchQuery,
        studentName: this.searchQuery
      }, {
        responseType: 'blob'
      })
      
      // 创建Blob对象
      const blob = new Blob([response.data], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      })
      
      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `学生获奖信息_${new Date().toLocaleDateString()}.xlsx`
      
      // 触发下载
      document.body.appendChild(link)
      link.click()
      
      // 清理
      setTimeout(() => {
        document.body.removeChild(link)
        URL.revokeObjectURL(link.href)
      }, 100)
      
      this.$message.success('导出成功')
    }
  },
  mounted() {
    this.fetchAwards()
  }
}
</script>

<style scoped lang="scss">
.banzhu-dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
  box-sizing: border-box;
}

.chart-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.table-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.table-title {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.table-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 10px;
}

.el-tag {
  font-weight: bold;
}

@media (max-width: 768px) {
  .table-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .table-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .el-input {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 10px;
  }
}
</style>